package com.chengzhi.eshopinventory.web;

import com.chengzhi.eshopinventory.entity.Inventory;
import com.chengzhi.eshopinventory.request.BaseRequest;
import com.chengzhi.eshopinventory.request.InventoryQueryRequest;
import com.chengzhi.eshopinventory.request.InventoryUpdateRequest;
import com.chengzhi.eshopinventory.service.InventoryAsyncService;
import com.chengzhi.eshopinventory.service.InventoryService;
import com.chengzhi.eshopinventory.thread.RequestThreadPool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * @description 库存
 * @author: ruanchengzhi
 * @create: 2021-04-01 17:14
 **/
@RestController
@RequestMapping("/inventory")
public class InventoryController {

    @Autowired
    private InventoryService inventoryService;

    @Autowired
    private InventoryAsyncService inventoryAsyncService;

    @PostMapping
    public Integer updateInventory(@RequestBody Inventory inventory) {
        inventoryAsyncService.precoss(new InventoryUpdateRequest(inventoryService, inventory));
        return 1;
    }

    @GetMapping("/{inventoryId}")
    public Inventory getInventoryById(@PathVariable Long inventoryId) {
        InventoryQueryRequest request = new InventoryQueryRequest(inventoryService, inventoryId, false);
        try {
            inventoryAsyncService.precoss(request);
            long startTime = System.currentTimeMillis();
            long endTime;
            while (true) {
                Inventory inventory = this.inventoryService.getRedisInventory(inventoryId);
                if (Objects.nonNull(inventory)) {
                    return inventory;
                } else {
                    Thread.sleep(20);
                    endTime = System.currentTimeMillis();
                    if ((endTime - startTime) > 200) {
                        break;
                    }
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Inventory inventory = inventoryService.getInventoryById(inventoryId);
        if (Objects.nonNull(inventory)) {
            //1.缓存被清理了 2.写请求没有被执行 3.数据库没有数据
            request = new InventoryQueryRequest(inventoryService, inventoryId, true);
            inventoryAsyncService.precoss(request);
            return inventory;
        }
        return null;
    }

}
